package com.crm.service.crm.businessOpportunities.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.model.common.constants.CustomInfoConstants;
import com.crm.model.common.dtos.PageResponseResult;
import com.crm.model.common.dtos.ResponseResult;
import com.crm.model.common.enums.AppHttpCodeEnum;
import com.crm.model.crm.businessOpportunities.dto.CustomInfoDto;
import com.crm.model.crm.businessOpportunities.dto.CustomInfoPageDto;
import com.crm.model.crm.businessOpportunities.dto.FishForDto;
import com.crm.model.crm.businessOpportunities.pojo.CustomInfo;
import com.crm.model.system.pojo.User;
import com.crm.model.system.role.pojo.Role;
import com.crm.service.crm.businessOpportunities.mapper.CustomInfoMapper;
import com.crm.service.crm.businessOpportunities.service.CustomInfoService;
import com.crm.service.system.mapper.UserMapper;
import com.crm.utils.ThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class CustomInfoServiceImpl extends ServiceImpl<CustomInfoMapper, CustomInfo> implements CustomInfoService {

    @Autowired
    private CustomInfoMapper customInfoMapper;

    @Autowired
    private UserMapper userMapper;


    //新增商机
    @Override
    public ResponseResult add(CustomInfoDto customInfoDto) {
        //健壮性判断
        if (customInfoDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (customInfoDto.getName() == null || customInfoDto.getPhone() == null || customInfoDto.getIntentionalDiscipline() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        
        //新建客户数据
        CustomInfo customInfo = new CustomInfo();
        //补充客户对象中的数据
        supplementCustomInfo(customInfoDto, customInfo);
        //插入数据
        customInfoMapper.insert(customInfo);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //补充商机字段
    private void supplementCustomInfo(CustomInfoDto customInfoDto, CustomInfo customInfo) {
        //复制字段
        BeanUtils.copyProperties(customInfoDto, customInfo);
        //补充字段
            //新建的商机没有归属人
        customInfo.setRevert(CustomInfoConstants.NOT_REVERT);
            //新建时间
        customInfo.setCreateTime(LocalDate.now());
            //新建人
        //从threadlocl中拿用户信息
        User user = ThreadLocalUtil.getUser();
//        customInfo.setCreatePeople(user.getName());
        customInfo.setCreatePeople("2");
        customInfo.setStatus(CustomInfoConstants.TO_BE_ALLOCATED);
    }

    //查询所有和高级查询
    @Override
    public ResponseResult getAll(CustomInfoPageDto customInfoPageDto) {
        //健壮性判断
        if (customInfoPageDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        
        //分页查询
        IPage page = new Page(customInfoPageDto.getPage(),customInfoPageDto.getSize());

        //条件查询
        LambdaQueryWrapper<CustomInfo> lambdaQueryWrapper = getInfoLambdaQueryWrapper(customInfoPageDto);
        
        //分页封装打包
        page = page(page,lambdaQueryWrapper);
        ResponseResult responseResult = new PageResponseResult(customInfoPageDto.getPage(),customInfoPageDto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    //条件判断
    private LambdaQueryWrapper<CustomInfo> getInfoLambdaQueryWrapper(CustomInfoPageDto customInfoPageDto) {
        //条件分页
        LambdaQueryWrapper<CustomInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //姓名校验
        if (customInfoPageDto.getName()!=null && !("").equals(customInfoPageDto.getName())){
            lambdaQueryWrapper.like(CustomInfo::getName, customInfoPageDto.getName());
        }
        //状态校验
        if (customInfoPageDto.getStatus()!=null && !("").equals(customInfoPageDto.getStatus())){
            lambdaQueryWrapper.eq(CustomInfo::getStatus, customInfoPageDto.getStatus());
        }
        //id校验
        if (customInfoPageDto.getId()!=null && !("").equals(customInfoPageDto.getId())){
            lambdaQueryWrapper.eq(CustomInfo::getId, customInfoPageDto.getId());
        }
        //phone校验
        if (customInfoPageDto.getPhone()!=null && !("").equals(customInfoPageDto.getPhone())){
            lambdaQueryWrapper.eq(CustomInfo::getPhone, customInfoPageDto.getPhone());
        }
        //归属人校验
        if (customInfoPageDto.getRevert()!=null && !("").equals(customInfoPageDto.getRevert())){
            lambdaQueryWrapper.eq(CustomInfo::getRevert, customInfoPageDto.getRevert());
        }
        //创建时间校验
        if (customInfoPageDto.getCreateTime()!=null && !("").equals(customInfoPageDto.getCreateTime())){
            lambdaQueryWrapper.eq(CustomInfo::getCreateTime, customInfoPageDto.getCreateTime());
        }
        return lambdaQueryWrapper;
    }

    //批量或单个分配，捞取
    @Override
    public ResponseResult addByRevertId(FishForDto fishForDto) {

        //健壮性判断
        if (fishForDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //获取选择的id集合
        List<Integer> ids = fishForDto.getIds();

        //判断是捞取还是分配
        if (fishForDto.getRevert() == null && fishForDto.getRevertId() == null ){
            //负责人名字和id都为空，则为捞取，存入当前登录的用户

            //判断是否达到上限
            if (fishForDto.getIds().size() >3){
                return ResponseResult.errorResult(AppHttpCodeEnum.NOT_UPPER_LIMIT);
            }
            //捞取到登录的用户
            fish(ids);
        }
        //如果有负责人名字和id，则为批量分配
        //判断是否达到上限
        if (ids.size()>3){
            return ResponseResult.errorResult(AppHttpCodeEnum.NOT_UPPER_LIMIT_2);
        }
        //分配给固定的员工
        distribute(fishForDto, ids);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //批量或单个分配
    private void distribute(FishForDto fishForDto, List<Integer> ids) {
        for (Integer customId : ids) {
            CustomInfo customInfo = customInfoMapper.selectById(customId);
            customInfo.setRevert(fishForDto.getRevert());
            customInfo.setRevertId(fishForDto.getRevertId());
            customInfo.setStatus(CustomInfoConstants.FOLLOW_UP);
            customInfoMapper.updateById(customInfo);
        }
    }

    //批量或单个捞取
    private void fish(List<Integer> ids) {
//        Integer id = ThreadLocalUtil.getUser().getId();
//        String name = ThreadLocalUtil.getUser().getName();
        Integer id = 1;
        String name = "a";
        for (Integer customId : ids) {
            CustomInfo customInfo = customInfoMapper.selectById(customId);
            customInfo.setRevert(name);
            customInfo.setRevertId(id);
            customInfo.setStatus(CustomInfoConstants.FOLLOW_UP);
            customInfoMapper.updateById(customInfo);
        }
    }

    //查询所有或高级查询没有被分配的商家（公海池中）
    @Override
    public ResponseResult getByNotRevert(CustomInfoPageDto customInfoPageDto) {
        //健壮性判断
        if (customInfoPageDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        
        //分页查询
        IPage page = new Page(customInfoPageDto.getPage(),customInfoPageDto.getSize());
        
        //条件校验
        LambdaQueryWrapper<CustomInfo> lambdaQueryWrapper = getCustomInfoLambdaQueryWrapper(customInfoPageDto);
        
        page = page(page,lambdaQueryWrapper);
        
        //分装打包
        ResponseResult responseResult = new PageResponseResult(customInfoPageDto.getPage(),customInfoPageDto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    //条件判断
    private LambdaQueryWrapper<CustomInfo> getCustomInfoLambdaQueryWrapper(CustomInfoPageDto customInfoPageDto) {
        //条件分页
        LambdaQueryWrapper<CustomInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //必须没有归属人(归属人为”“的信息)
        customInfoPageDto.setRevert("");
        lambdaQueryWrapper.eq(CustomInfo::getRevert, customInfoPageDto.getRevert());
        //条件查询判断
        //姓名校验
        if (customInfoPageDto.getName()!=null && !("").equals(customInfoPageDto.getName())){
            lambdaQueryWrapper.like(CustomInfo::getName, customInfoPageDto.getName());
        }
        //id校验
        if (customInfoPageDto.getId()!=null && !("").equals(customInfoPageDto.getId())){
            lambdaQueryWrapper.eq(CustomInfo::getId, customInfoPageDto.getId());
        }
        //phone校验
        if (customInfoPageDto.getPhone()!=null && !("").equals(customInfoPageDto.getPhone())){
            lambdaQueryWrapper.eq(CustomInfo::getPhone, customInfoPageDto.getPhone());
        }
        //意向学科校验
        if (customInfoPageDto.getIntentionalDiscipline()!=null && !("").equals(customInfoPageDto.getIntentionalDiscipline())){
            lambdaQueryWrapper.eq(CustomInfo::getIntentionalDiscipline, customInfoPageDto.getIntentionalDiscipline());
        }
        //创建时间校验
        if (customInfoPageDto.getCreateTime()!=null && !("").equals(customInfoPageDto.getCreateTime())){
            lambdaQueryWrapper.eq(CustomInfo::getCreateTime, customInfoPageDto.getCreateTime());
        }
        return lambdaQueryWrapper;
    }

    //查询所有公共字段
    @Override
    public ResponseResult getAllCommont() {
        //查询归属人(即角色为员工的用户)
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getRoleName,"员工");
        List<User> revert = userMapper.selectList(lambdaQueryWrapper);

        return null;
    }
}
